package router

import (
	"demo/pkg/middleware"
	"demo/services"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/rs/cors"
)

func SetupRouters() *gin.Engine {
	r := gin.Default()

	// 设置CORS中间件，允许所有跨域请求
	corsMiddleware := cors.New(cors.Options{
		AllowedOrigins:   []string{"*"},
		AllowedMethods:   []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
		AllowedHeaders:   []string{"*"},
		AllowCredentials: true,
	})

	// 包装gin的处理器
	r.Use(func(c *gin.Context) {
		corsMiddleware.HandlerFunc(c.Writer, c.Request)
		if c.Request.Method == http.MethodOptions {
			c.AbortWithStatus(http.StatusNoContent)
			return
		}
		c.Next()
	})

	noAuth := r.Group("/v1")
	auth := r.Group("/v1")
	auth.Use(middleware.CheckLogin())
	//登录
	noAuth.POST("/login", services.LoginPostService)
	//注册
	noAuth.POST("/register", services.RegisterPostService)
	//模糊或精确搜索
	noAuth.POST("/search", services.SearchUser)
	//获取用户信息
	auth.GET("/userinfo", services.GetUserInfo)
	//修改用户信息
	auth.PUT("/userinfo", services.UpdateUserinfo)
	//邮箱验证接口
	auth.GET("/auth_code", services.SendEmailCode)
	//修改密码
	auth.PUT("/password", services.UpadatePassword)
	//管理员输入账单信息
	noAuth.POST("/calculate_ele", services.CalculateElectricityBillService)
	//获取所有用户信息
	noAuth.GET("/userinfos", services.GetAllUsersInfo)
	//用户查询账单
	auth.GET("/bill", services.GetElectricityBillsService)
	//用户支付账单
	auth.POST("/paybill", services.PayElectricityBillService)
	//用电分析报告
	auth.GET("/report", services.ElectricityUsageReport)
	//获取用户所有通知
	auth.GET("/notices", services.GetAllNotices)
	//更新用户通知状态
	auth.PUT("/notice", services.UpadateNoticestatus)
	//获取用户每月用电量
	auth.GET("/month_usage", services.MonthlyElectricityUsage)
	//获取用户用电信息
	auth.GET("/user_ele", services.GetUserEleInfo)
	//获取用户最新的用户报告
	auth.GET("/latest_report", services.GetLatestReport)
	//给用户发送支付成功的通知
	noAuth.POST("/ok_pay/send/:id", services.OkPay)
	//获取所有的用户账单
	noAuth.GET("/all_bill", services.GetAllBills)
	//获取所有用户的支付信息
	noAuth.GET("/all_payment", services.GetAllPayments)
	//生成管理员用户所需信息
	noAuth.GET("/admin_info", services.GenerateAdminInfo)
	//生成管理员所需的总报告
	noAuth.GET("/admin_report", services.GenerateAdminReport)
	return r
}
